package com.bawei.movie.vm

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.bawei.common.entity.MovieVideoEntity
import com.bawei.common.vm.BaseViewModel
import com.bawei.movie.intent.MovieViewIntent
import com.bawei.movie.model.MoviePagingSource
import com.bawei.movie.model.MovieRepository
import com.bawei.movie.state.MovieUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2025/2/8
 * Desc:
 */
@HiltViewModel
class MovieViewModel @Inject constructor(private val repository: MovieRepository): BaseViewModel<MovieViewIntent>() {

    private val _uiState = MutableStateFlow<MovieUiState>(MovieUiState.LoadEmpty)
    val uiState: StateFlow<MovieUiState> = _uiState.asStateFlow()

    override fun dispatchIntent(intent: MovieViewIntent) {
        when(intent){
            is MovieViewIntent.LoadLeverOneType -> loadLeverOneType()
            is MovieViewIntent.LoadLeverTwoType -> loadLeverTwoType(intent.pid)
        }
    }

    private fun loadLeverOneType() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                //使用对象属性字段解构，注意解构出来字段名和顺序必须一致
                val (code, data, msg) = repository.getMutilType()
                //切换到主线程中执行
                withContext(Dispatchers.Main){
                    if (code == 0 && data.isNotEmpty()){
                        _uiState.value = MovieUiState.LoadLeverOneTypeSuccess(data)
                    }else{
                        _uiState.value = MovieUiState.LoadLeverOneTypeFail(msg)
                    }
                }

            } catch (e: Exception){
                withContext(Dispatchers.Main){
                    _uiState.value = MovieUiState.LoadLeverOneTypeFail("请求失败")
                }
            } finally {
                this.cancel()
            }
        }
    }


    private fun loadLeverTwoType(pid: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                //使用对象属性字段解构，注意解构出来字段名和顺序必须一致
                val (code, data, msg) = repository.getMutilTypeById(pid)
                //切到主线程中执行
                withContext(Dispatchers.Main){
                    if (code == 0 && data.isNotEmpty()){
                        _uiState.value = MovieUiState.LoadLeverTwoTypeSuccess(data)
                    }else{
                        _uiState.value = MovieUiState.LoadLeverTwoTypeFail(msg)
                    }
                }

            } catch (e: Exception){
                withContext(Dispatchers.Main){
                    _uiState.value = MovieUiState.LoadLeverTwoTypeFail("请求失败")
                }
            } finally {
                this.cancel()
            }
        }
    }

    /**
     * 获取推荐电影列表
     */
    fun loadRecommendVideo(): Flow<PagingData<MovieVideoEntity>>{
        return Pager(config = PagingConfig(initialLoadSize = 1, pageSize = 10, enablePlaceholders = false), pagingSourceFactory = { MoviePagingSource()}).flow.cachedIn(viewModelScope)
    }


    /**
     * 获取分类电影列表
     */
    fun loadMutilVideoById(typeId: Int): Flow<PagingData<MovieVideoEntity>>{
        return Pager(config = PagingConfig(initialLoadSize = 1, pageSize = 10, enablePlaceholders = false), pagingSourceFactory = { MoviePagingSource(typeId)}).flow.cachedIn(viewModelScope)
    }






}